import functools
from requests import request
from rest_framework.request import Request
from rest_framework.response import Response as originalResponse
from core.log import logging
def headerChecking(rule:list):
    '''检查request
    args:\r\n
    \trule:<class:dict>,["query.key1","query.key2",'header.key1','header.key2','data.key1.key2']
    '''
    def decorator(func):
        @functools.wraps(func)
        def wapper(*args,**kwargs):
            assert isinstance(rule,list), "haderChecking rule must list type."
            request= None
            for o in args:
                if isinstance(o,Request):
                    request= o
                    break
            if not request:
                return originalResponse({'state':-1, 'msg':'not found request object.'})
            result={"state":200,'msg':[]}
            for o in rule:
                r1= str.split(o,".")
                if len(r1)>1:
                    if r1[0].lower()=="query":
                        if r1[1] not in request.query_params:
                            result['state']=-1
                            result['msg'].append("request.query_params not found %s"%r1[1])
                    elif r1[0].lower()=="header":
                        if not r1[1].upper().startswith('HTTP_'):
                            r1[1]= "".join(["HTTP_",r1[1]])
                        r1[1]=r1[1].replace('-',"_")
                        if r1[1].upper() not in request.META:
                            result['state']=-1
                            result['msg'].append("request.META not found %s"%r1[1])
                    elif r1[0].lower()=="data":
                        tmp_data= request.data
                        for v in r1[1:len(r1)]:
                            if v in tmp_data:
                                tmp_data= tmp_data[v]
                            else:
                                result['state']=-1
                                result['msg'].append("request.META not found %s"% o)
                    else:
                        result['state']=-1
                        assert False, "rule target is error, prefix must query or header."
                else:
                    result['state']=-1
                    assert False, "rule is error. formatter:['query.key1','query.key2','header.key1','header.key2','data.key1.key2']"
            if result['state']!=200:
                return originalResponse(result)
            return func(*args,**kwargs)
        return wapper
    return decorator